<template>
  <div class="business-information-map">
    <div id="allmap"></div>
    <div class="query-box">
      <div class="tabs">
        <div :class="{on:tabValue === 'project'}" class="tabs-item" @click="onTabs('project')">
          <img src="../../../assets/icon/icon-user-details-04.png" />
          <span>项目</span>
        </div>
        <div :class="{on:tabValue === 'company'}" class="tabs-item" @click="onTabs('company')">
          <img src="../../../assets/icon/icon-user-details-02.png" />
          <span>公司</span>
        </div>
      </div>

      <Form ref="formData" v-show="!isDetailsPage">
        <Row>
          <div class="search-input">
            <FormItem v-show="tabValue === 'project'">
              <Input search placeholder="搜索关键词" v-model="projectName" />
            </FormItem>
            <FormItem v-show="tabValue === 'company'">
              <Input search placeholder="搜索关键词" v-model="companyName" />
            </FormItem>
          </div>
          <div span="10" class="com-action-search-btn">
            <Button icon="md-search" type="primary" @click="handleSubmit">查询</Button>
            <BtnPlain class="bg-white" type="primary" @click="handleReset">
              <Icon type="md-refresh" />
              <span>重置</span>
            </BtnPlain>
          </div>
        </Row>
      </Form>

      <div class="data-list" v-show="!isDetailsPage">
        <ul v-show="tabValue === 'project'">
          <li class="card" v-for="it in projectList" :key="it.busInfoTrackId">
            <ProjectItem :info="it" :tabValue="tabValue" />
          </li>
        </ul>

        <ul v-show="tabValue === 'company'">
          <li class="card" v-for="it in companyList" :key="it.companyId">
            <CompanyItem :info="it" @showDetails="showDetails" @hideDetails="hideDetails" @view="onView" />
          </li>
        </ul>
      </div>

      <div class="right-details" :style="`top:${clientY}px`" v-show="isDetails">
        <h3>{{ info.companyName }}</h3>
        <div>{{ info.companyAddress }}</div>
        <div class="right-details-content">
          <Row>
            <Col span="12">
              <span class="label">服务地区:</span>
              <span>{{ info.city }}</span>
            </Col>
            <Col span="12">
              <span class="label">产业标记:</span>
              <span>{{ info.industryName }}</span>
            </Col>
            <Col span="12">
              <span class="label">经营信息:</span>
              <span>{{ info.projectCount }}</span>
            </Col>
            <Col span="12">
              <span class="label">收益规则:</span>
              <span>{{ info.companyDivideIntoRuleValue }}%</span>
            </Col>
          </Row>
        </div>
      </div>

      <div class="data-list" v-show="isDetailsPage">
        <ul>
          <li class="card">
            <Row align="middle">
              <BtnPlain class="com-action-btn" type="primary" @click="goBack">返回</BtnPlain>
              <h3>公司经营信息详情</h3>
            </Row>
          </li>
          <li class="card">
            <CompanyItem :info="companyInfo" @showDetails="showDetails" @hideDetails="hideDetails" @view="onView" />
          </li>
          <li class="card" v-for="it in detailsPageProjectList" :key="it.busInfoTrackId">
            <ProjectItem :info="it" :tabValue="tabValue" />
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import ProjectItem from './projectItem.vue'
import CompanyItem from './companyItem.vue'
import { busiInfoMapGetByPage, busiInfoMapGetBusInfoTraceCountByCompany, busiInfoMapGetBusiInfoTrackByPage } from '@/api/businessInformationManage.js'

export default {
  name: 'businessInformationMap',
  components: { ProjectItem, CompanyItem },
  data () {
    return {
      cluster: null,
      map: null,
      tabValue: 'project',
      projectName: '',
      companyName: '',
      // 详情悬浮框
      isDetails: false,
      projectList: [],
      companyList: [],
      info: {},
      clientY: 100,
      // 详情页
      isDetailsPage: false,
      companyInfo: {},
      detailsPageProjectList: {},
      projectTrackList: []
    }
  },
  created () {
    this.getProject()
    this.getCompany()
  },
  mounted () {
    this.setMap()
  },
  methods: {
    setMap () {
      this.map = new BMapGL.Map('allmap');
      this.map.centerAndZoom(new BMapGL.Point(100, 34), 6);
      this.map.enableScrollWheelZoom(true);
    },
    onTabs (value) {
      this.tabValue = value
      this.isDetailsPage = false
      if (value === 'project') {
        this.addCluster(this.projectList)
        return
      }
      this.addCluster(this.projectTrackList)
    },
    handleReset () {
      if (this.tabValue === 'project') {
        this.projectName = ''
        this.getProject()
        return
      }
      this.companyName = ''
      this.getCompany()
    },
    handleSubmit () {
      if (this.tabValue === 'project') {
        this.getProject()
        return
      }
      this.getCompany()
    },
    async getProject () {
      const { data } = await busiInfoMapGetByPage({ projectName: this.projectName, size: 9999 })
      this.projectList = data
      this.addCluster(data)
    },
    async getCompany () {
      const data = await busiInfoMapGetBusInfoTraceCountByCompany({ companyName: this.companyName })
      this.projectTrackList = []
      this.companyList = data.map(it => {
        this.projectTrackList = [...this.projectTrackList, ...it.projectTrackList]
        return it.companyTreeVoList[0]
      })
    },

    showDetails (data, clientY) {
      this.info = data
      this.clientY = clientY - 120
      this.isDetails = true
    },
    hideDetails () {
      this.isDetails = false
    },
    async onView (info) {
      if (this.companyInfo.companyId === info.companyId) return
      const { data } = await busiInfoMapGetBusiInfoTrackByPage({ companyId: info.companyId, size: 9999 })
      this.companyInfo = info
      this.detailsPageProjectList = data
      this.isDetailsPage = true
      this.addCluster(data)
    },
    goBack () {
      this.isDetailsPage = false
      this.addCluster(this.projectTrackList)
    },
    addCluster (projectList) {
      this.$nextTick(() => {
        if (this.cluster) {
          this.removeCluster()
        }
        this.cluster = new Cluster.View(this.map,
          {
            clusterMinPoints: 1,
            clusterMaxZoom: 16,
            updateRealTime: true,
            fitViewOnClick: true,
            clusterType: [
              [3, 10, Cluster.ClusterType.ATTR_REF, ['province']],
              [11, 12, Cluster.ClusterType.ATTR_REF, ['city', 'area']],
              [13, null, Cluster.ClusterType.GEO_FENCE, []]
              // [13, null, Cluster.ClusterType.DIS_PIXEL, 64]
            ],
            renderClusterStyle: {
              type: Cluster.ClusterRender.DOM,
              style: {
                anchors: [0, 1],
                offsetX: -20,
                offsetY: -9.5
              },
              inject: this.getHTMLDOM
            },
            renderSingleStyle: {
              type: Cluster.ClusterRender.DOM,
              style: {
                anchors: [0, 1],
                offsetX: -20,
                offsetY: -9.5
              },
              inject: this.getHTMLDOM
            }
          });

        this.cluster.on(Cluster.ClusterEvent.MOUSE_OVER, (e) => {
          const { isCluster, latLng, properties } = e
          if (isCluster) return

          this.map.removeOverlay(this.customOverlay)
          // 创建自定义覆盖物
          this.customOverlay = new BMapGL.CustomOverlay(this.createDOM, {
            point: new BMapGL.Point(latLng[0], latLng[1]),
            opacity: 0.5,
            offsetY: -10,
            properties
          });

          this.map.addOverlay(this.customOverlay);

          // 查看详情添加事件
          document.querySelectorAll('.custom-overlay-btn').forEach((it, i) => {
            it.addEventListener('click', () => {
              const { busiInfoId, busInfoTrackId } = properties.repeatList[i]

              if (this.tabValue === 'project') {
                this.$router.push({ path: '/businessInformationDetails', query: { busiInfoId, type: 'view', page: 'businessInformationMap' } })
              } else {
                this.$router.push({ path: '/businessInfoTrackDetails', query: { busInfoTrackId, type: 'view', page: 'businessInformationMap' } })
              }
            })
          })
        });
        // 监听地图缩放
        this.map.addEventListener('zoomend', (e) => {
          this.map.removeOverlay(this.customOverlay)
        })

        // 统计去重后的省份列表
        const provinceList = new Set()
        // 去除重复坐标
        const newList = []
        projectList.forEach(item => {
          provinceList.add(item.province)
          const index = newList.findIndex(it => item.longitude === it.longitude && item.latitude === it.latitude)
          if (index < 0) {
            newList.push({
              ...item,
              repeatList: [item]
            })
          } else {
            newList[index].repeatList.push(item)
          }
        })

        var points = Cluster.pointTransformer(newList, (it) => {
          return {
            point: [it.longitude * 1, it.latitude * 1],
            properties: {
              name: it.projectName,
              address: it.projectAddressName,
              province: it.province,
              city: it.city,
              busiInfoId: it.busiInfoId,
              busInfoTrackId: it.busInfoTrackId,
              repeatList: it.repeatList
            }
          }
        });
        // 只有一个省, 就以省为中心
        const arr = Array.from(provinceList)
        if (arr.length === 1) {
          this.map.centerAndZoom(arr[0]);
        } else {
          this.map.centerAndZoom(new BMapGL.Point(100, 34), 6);
        }
        this.cluster.setData(points);
      })
    },
    getHTMLDOM (context = {}) {
      var count = context.pointCount || 1; // 聚合中点的总数
      var type = context.type; // 聚合中点的总数

      var div = document.createElement('div');
      div.className = 'cluster-marker';
      var content = '';
      if (type !== 'geo-fence') {
        content += `<span class="cluster-marker-body">` + count + '</span>';
      } else {
        content += '<span class="cluster-marker-title"></span>';
      }

      div.innerHTML = content;
      return div;
    },
    createDOM (properties) {
      var div = document.createElement('div');
      div.className = 'custom-overlay-box';
      var content = '';
      properties.repeatList.forEach((it, i) => {
        content += `
        <div class="custom-overlay-title">
          <p class="custom-overlay-name">项目名: ${it.projectName}</p>
          <p class="custom-overlay-btn">查看详情</p> 
        </div>`;
      })

      content += '<div class="custom-overlay-text">地址: ' + properties.address + '</div>';
      div.innerHTML = content;

      return div;
    },
    // 移除聚合数据
    removeCluster () {
      this.cluster && this.cluster.destroy();
      this.cluster = null;
    }
  }
}
</script>

<style lang='less' scoped>
.business-information-map {
  position: relative;
  height: 800px;
  z-index: 0;

  .bg-white {
    background-color: #fff;
  }

  .right-details {
    position: absolute;
    right: -550px;
    width: 532px;
    line-height: 30px;
    padding: 10px 20px;
    background-color: #fff;
    border-radius: 4px;
    z-index: 99;

    .label {
      margin-right: 15px;
      color: #7b8591;
    }
  }
  .right-details-content {
    padding: 10px;
    background-color: #f1f8ff;
    border-radius: 4px;
  }
}
#allmap {
  width: 100%;
  height: 100%;
}

.query-box {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 532px;
  z-index: 99;

  .tabs {
    display: flex;
    padding: 5px;
    border-radius: 4px;
    margin-bottom: 10px;
    background-color: #fff;
  }

  .tabs-item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50%;
    padding: 5px;
    border-radius: 4px;
    cursor: pointer;

    &.on {
      background-color: #f7f8fa;
    }
    > img {
      width: 21px;
      height: 21px;
      margin-right: 20px;
    }
  }
}

.search-input {
  flex: 1;
}

.data-list {
  max-height: 700px;
  overflow: scroll;

  .card {
    line-height: 30px;
    padding: 10px 20px;
    margin-bottom: 10px;
    background-color: #fff;
    border-radius: 4px;
  }
}
</style>

<style lang="less">
.business-information-map {
  .ivu-input {
    background-color: #fff;
    margin-right: 0;
  }

  .ivu-form-item {
    margin-bottom: 10px;
  }

  .cluster-marker {
    position: absolute;
    left: 8px;
    top: 15px;
  }

  .cluster-marker-title {
    display: inline-block;
    width: 20px;
    height: 20px;
    background-color: skyblue;
    border-radius: 5px 0 0 0;
    cursor: pointer;
    background: url('../../../assets/icon/icon-locate.png') no-repeat;
    background-size: 100% 100%;
  }

  .cluster-marker-body,
  .cluster-marker-body-content {
    display: inline-block;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    color: #fff;
    font-size: 18px;
    white-space: nowrap;
    border-radius: 50%;
    background-color: #0052d9;
  }

  .cluster-marker-body-content {
    width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
  }

  .icon {
    width: 20px;
    height: 20px;
    background-color: #eee;
  }
}

.custom-overlay-box {
  position: absolute;
  top: -40px;
  left: 0px;
  width: auto;
  min-width: 400px;
  padding: 10px;
  background-color: #fffeef;
  border-radius: 5px;
}

.custom-overlay-name {
  min-width: 320px;
  text-overflow: ellipsis; /* 溢出显示省略号 */
  overflow: hidden; /* 溢出隐藏 */
  white-space: nowrap; /* 强制不换行 */
}

.custom-overlay-btn {
  color: #0052d9;
  cursor: pointer;
}
.custom-overlay-text {
  margin-top: 10px;
  white-space: nowrap;
}

.custom-overlay-title {
  display: flex;
  justify-content: space-between;
  font-weight: 500;
  margin-bottom: 2px;
}
</style>
